package net.dntuan.resttemplate;

import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.client.DefaultResponseErrorHandler;

/**
 * @author tuan.dangnhu
 *
 * $LastChangedRevision: 94 $ <br>
 * $LastChangedDate: 2014-04-29 10:18:50 +0000 (Tue, 29 Apr 2014) $
 */
public class CustomResponseErrorHandler extends DefaultResponseErrorHandler {

  private static final Logger LOGGER = LoggerFactory.getLogger(CustomResponseErrorHandler.class);

  @Override
  public void handleError(ClientHttpResponse response) throws IOException {
    LOGGER.error(String.format("Code: %s, response text: %s", response.getRawStatusCode(), new String(
        getResponseBody(response))));
    super.handleError(response);
  }

  protected byte[] getResponseBody(ClientHttpResponse response) {
    try {
      InputStream responseBody = response.getBody();
      if (responseBody != null) {
        return FileCopyUtils.copyToByteArray(responseBody);
      }
    } catch (IOException ex) {
      // ignore
    }
    return new byte[0];
  }
}
